package algorithms.sort;

/**
 * @author glogo
 *
 */
public class FindIndexAhead {

	public static Comparable select(Comparable[] a, int k){
		int lo = 0; 
		int hi = a.length - 1;
		while(lo < hi){
			int j = partition(a, lo, hi);
			if(j == k)	return a[k];
			else if(j < k)	lo = j + 1;
			else if(j > k)	hi = j - 1;
		}
		return a[k];
	}
	
	
	private static int partition(Comparable[] a, int lo, int hi){
		int i = lo;
		int j = hi + 1;
		Comparable v = a[lo];
		
		while(true){
			while(less(a[++i], v))
				if(i == hi)	break;
			while(less(v, a[--j]))
				if(j == lo) break;
			if(i >= j)	break;
			exch(a, i, j);
		}
		exch(a, lo, j);
		return j;
	}
	
	private static void exch(Comparable[] a, int i, int j){
		Comparable tmp = a[i];
		a[i] = a[j];
		a[j] = tmp;
	}
	
	private static boolean less(Comparable v, Comparable w){
		return v.compareTo(w) < 0;
	}
	
	public static void show(Comparable[] a){
		for(Comparable t : a)
			System.out.print(t + " ");
	}
	
	public static void main(String[] args) {
		Integer[] a = {5,4,3,2,1};
		System.out.println(FindIndexAhead.select(a, 0));	
//		FindIndexAhead.show(a);
	}

}
